package org.example.lesson;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.Socket;
import java.util.Scanner;

public class TCPEchoClient {
    //声明Socket对象
    private Socket socket;
    public TCPEchoClient(String serverIp,int serverPort) throws IOException {
        //检验
        if(serverIp==null||serverIp.isEmpty()){
            throw new BindException("Ip地址不能为空.");
        }
        if(serverPort<1024||serverPort>65535){
            throw new BindException("端口号必须在1024和65535之间.");
        }
        //根据服务器IP和端口号初始化Socket对象
        this.socket=new Socket(serverIp,serverPort);
    }
    public void start(){
        System.out.println("客户端已启动.");
        //从Socket对象中获取输入与输出流对象
        try(InputStream inputStream=this.socket.getInputStream();
            OutputStream outputStream=this.socket.getOutputStream()){
            //1.循环接收用户的输入
            while(true){
                System.out.println("->");
                Scanner in=new Scanner(System.in);
                String request=in.nextLine();
                //非空校验
                if(request==null||request.isEmpty()){
                    System.out.println("输入的内容不能为空.");
                    continue;
                }
                //2.把用户的输入封装到输出流中，可以用PrintWriter进行简化
                PrintWriter writer=new PrintWriter(outputStream);
                //3.把数据写入到输出流中
                writer.println(request);
                //4.强制刷新缓冲区，到此请求发送完成
                writer.flush();
                //5.准备接收服务器返回的响应数据，通过输入流创建用于读取响应的对象
                Scanner responseScanner=new Scanner(inputStream);
                //6.解析响应数据
                String response=responseScanner.nextLine();
                //7.打印日志
                System.out.printf("request=%s,response=%s\n",request,response);
                //关闭流之后表示客户端下线
//                in.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TCPEchoClient client=new TCPEchoClient("127.0.0.1",9090);
        client.start();
    }
}
